/*
 * GeoVISTA Center (Penn State, Dept. of Geography)
 * Copyright (c) 2002, GeoVISTA Center
 * Licensed under Simplified BSD License
 * This library is developed and distributed for free usage,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 * You can redistribute and/or modify it under the terms of the
 * Simplified BSD License
 *
 *
 *
 *
 *
 *
 *
 * @original author: jin Chen 
 * @author: jin Chen 
 * @date: Nov 19, 2008$
 * @version: 1.0
 */
package edu.psu.geovista.app.vit.pub.components.ptnbskt;

import edu.psu.geovista.app.gmatrix.app.DendroMatrix;
import edu.psu.geovista.app.hce.clustering.hierarchical.AgglomerativeClusteringpub;
import edu.psu.geovista.app.hce.clustering.model.BCluster;
import edu.psu.geovista.app.hce.clustering.model.DfLCluster;
import edu.psu.geovista.app.hce.clustering.normalize.Normalizer;
import edu.psu.geovista.app.vit.pub.VitPub;
import edu.psu.geovista.app.vit.pub.utils.VitUtils;
import edu.psu.geovista.common.utils.collection.CollectionUtils;
import edu.psu.geovista.components.selection.ActionOnSelection;
import edu.psu.geovista.data.model.AppDataModel;
import edu.psu.geovista.data.model.DefaultAppDataModel;
import edu.psu.geovista.ui.event.SelectionEvent;
import edu.psu.geovista.ui.event.SelectionListener;

import javax.swing.*;
import java.awt.*;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.HashSet;
import java.util.Map;
import java.util.Properties;
import java.util.Set;

public class MyBasket extends JPanel implements SelectionListener {
    static final String Method_UNION = "Union(add all)";
    static final String Method_INTERSECTION = "Intersection(retain all)";
    public static final String TITLE= "Selection Basket";
    transient MySelectionTable itemTable;
    transient String root;// 
    transient int[] selection;// 
    transient ActionOnSelection action;
    Persistool pm;
    VitPub vit;

   public MyBasket(VitPub vit) {
       this.vit=vit;
      // this.setLayout(new BorderLayout());
        initComponents();
        customizeGUI();
    }

    private void customizeGUI(){
       pm=new Persistool();
       pm.setBsk(this);
       itemTable = MySelectionTable.getDefaultSelectionTable();
       JScrollPane sp=new JScrollPane(itemTable);
       //MainPane.add(sp);
       this.mainSplit.setTopComponent(sp);
      // evenfier=new GeoVistaEventFirer(this);
   }


    /*******************************************************************************************************
     *                functions
     *******************************************************************************************************/
    /**
     *  
     *
     */
    public void addSelection( int[] selection){
        HashSet selected = CollectionUtils.convertArrayToSet(selection);
        itemTable.addDataGroup(null,selected);
    }

    public void update(){
        int[] selectedrows = this.itemTable.getSelectedRows();
        if(selectedrows.length !=1){
            JOptionPane.showMessageDialog(null,"You can update only one row at a time. Please select only one row");
            return;
        }
        else{
            int row = selectedrows[0];
            String desc = this.descArea.getText();
            itemTable.setValueAt(desc,row, "Description");
            try {
               pm.save();
            } catch (IOException e) {
                e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
            }
        }
    }
    public void save()  {
        try {
            pm.save();
        } catch (IOException e) {
            e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
        }
    }
       public void addSelectionListener (SelectionListener l) {          //addSelectionListener
                (  (MySelectionTable) this.itemTable).addSelectionListener(l); //setId2IndexMap

       }

       /**
        * removes an SelectionListener from the component
        */
       public void removeSelectionListener (SelectionListener l) {
            ((MySelectionTable) this.itemTable).removeSelectionListener(l); //setId2IndexMap

       }
    public void fireSelection(){
         ((MySelectionTable)this.itemTable).fireEvents();
    }

    /**
     *  
     * @param event
     */
    public void selectionChanged(SelectionEvent event) {
       selection = event.getSelection();
    }
    public void setId2Index(Map<Object,Integer> id2index){
         ((MySelectionTable)this.itemTable).setId2IndexMap(id2index);
    }
    public void load() throws FileNotFoundException{
      String fn = getPersistentFileName();
         File file = new File(fn);
         if(file.exists() )
            pm.load(file);

    }


    private void combineSelection(){
       // if(combMethodPane==null)combMethodPane=new AskCombineSelectionPane();
      final JComboBox box=new JComboBox(new Object[]{Method_INTERSECTION,Method_UNION});
        box.setSelectedIndex(0);
        int v = VitUtils.showDialog(this, box, "Select a method to combine the selections", null);
        if(v==JOptionPane.OK_OPTION){

            int[] selrows = itemTable.getSelectedRows();
            Set selectedIds = itemTable.getSelectedId(selrows);
            int[] dataIndex =null;
            if(box.getSelectedItem().equals(Method_UNION)){
                dataIndex = itemTable.getSelectedDataIndex(selectedIds);
            }
            else if(box.getSelectedItem().equals(Method_INTERSECTION)){
                dataIndex = itemTable.getSelectedUnionDataIndex(selectedIds);

            }
            this.addSelection(dataIndex);
        }


    }

    /*******************************************************************************************************
     *                getter
     *******************************************************************************************************/
    public  Map<Object, Set> getSelections() {
        return itemTable.getDataGroups();
    }
     public  Map<Object, Properties> getAttributes() {
        return itemTable.getTableAttrbites();
    }
    public void setSelections(Map<Object, Set> dg,Map<Object, Properties> dps){
        itemTable.setDataGroups(dg,dps);
    }
     public void setProjectRoot(String proot) {
       this.pm.setRoot(proot);
    }

    public void setAction(ActionOnSelection action) {
        this.action = action;

    }
    public String getPersistentFileName() {
        String fn = this.getRoot() + File.separator + "selections.xml";
        return fn;
    }


    public String getRoot() {
        return root;
    }

    public void setRoot(String root) {
        this.root = root;
         this.pm.setRoot(root);
    }

  
    /*******************************************************************************************************
     *                GUI
     *******************************************************************************************************/

      /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc="Generated Code">
    private void initComponents() {

        jScrollPane2 = new javax.swing.JScrollPane();
        jTextArea1 = new javax.swing.JTextArea();
        MainPane = new javax.swing.JPanel();
        mainSplit = new javax.swing.JSplitPane();
        jPanel1 = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        jScrollPane3 = new javax.swing.JScrollPane();
        descArea = new javax.swing.JTextArea();
        toolBar = new javax.swing.JToolBar();
        addBtn = new javax.swing.JButton();
        rmvBtn = new javax.swing.JButton();
        updtBtn = new javax.swing.JButton();
        selBtn = new javax.swing.JButton();
        combBtn = new javax.swing.JButton();
        clsBtn = new javax.swing.JButton();

        jTextArea1.setColumns(20);
        jTextArea1.setRows(5);
        jScrollPane2.setViewportView(jTextArea1);

        MainPane.setBorder(javax.swing.BorderFactory.createEtchedBorder());

        mainSplit.setDividerLocation(90);
        mainSplit.setOrientation(javax.swing.JSplitPane.VERTICAL_SPLIT);

        jTable1.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
        ));
        jScrollPane1.setViewportView(jTable1);

        org.jdesktop.layout.GroupLayout jPanel1Layout = new org.jdesktop.layout.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(jPanel1Layout.createSequentialGroup()
                .add(jScrollPane1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 611, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(jPanel1Layout.createSequentialGroup()
                .add(jScrollPane1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 206, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addContainerGap(org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        mainSplit.setLeftComponent(jPanel1);

        descArea.setColumns(20);
        descArea.setRows(5);
        jScrollPane3.setViewportView(descArea);

        mainSplit.setRightComponent(jScrollPane3);

        org.jdesktop.layout.GroupLayout MainPaneLayout = new org.jdesktop.layout.GroupLayout(MainPane);
        MainPane.setLayout(MainPaneLayout);
        MainPaneLayout.setHorizontalGroup(
            MainPaneLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(MainPaneLayout.createSequentialGroup()
                .addContainerGap()
                .add(mainSplit, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 613, Short.MAX_VALUE)
                .addContainerGap())
        );
        MainPaneLayout.setVerticalGroup(
            MainPaneLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(MainPaneLayout.createSequentialGroup()
                .add(mainSplit, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 396, Short.MAX_VALUE)
                .add(22, 22, 22))
        );

        addBtn.setText("Add");
        addBtn.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                addBtnActionPerformed(evt);
            }
        });
        toolBar.add(addBtn);

        rmvBtn.setText("Remove");
        rmvBtn.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                rmvBtnActionPerformed(evt);
            }
        });
        toolBar.add(rmvBtn);

        updtBtn.setText("Update");
        updtBtn.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                updtBtnActionPerformed(evt);
            }
        });
        toolBar.add(updtBtn);


        combBtn.setText("Combine");
        combBtn.setToolTipText("Generate new selection based on currently selected data");
        combBtn.setFocusable(false);
        combBtn.setHorizontalTextPosition(javax.swing.SwingConstants.CENTER);
        combBtn.setVerticalTextPosition(javax.swing.SwingConstants.BOTTOM);
        combBtn.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                combBtnActionPerformed(evt);
            }
        });
        toolBar.add(combBtn);

        clsBtn.setText("Cluster");
        clsBtn.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                clsBtnActionPerformed(evt);
            }
        });
        toolBar.add(clsBtn);

        org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(toolBar, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 637, Short.MAX_VALUE)
            .add(MainPane, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(layout.createSequentialGroup()
                .add(toolBar, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 23, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(MainPane, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
    }// </editor-fold>

     private void rmvBtnActionPerformed(java.awt.event.ActionEvent evt) {
          int[] selrows = this.itemTable.getSelectedRows();
          itemTable.removeRows(selrows);
      }

      private void addBtnActionPerformed(java.awt.event.ActionEvent evt) {
            this.addSelection( selection);
      }

       private void updtBtnActionPerformed(java.awt.event.ActionEvent evt) {
            this.update();
    }

    private void clsBtnActionPerformed(java.awt.event.ActionEvent evt) {
        int[] dataIndexs = itemTable.getSelectedDataIndexs();
       /* this.action.setSelection(dataIndexs);
        ((ActionListener)action).actionPerformed(evt);*/

        AppDataModel app=vit.getDataModel();
        int columncount = app.getColumnCount();
        if(dataIndexs.length <=0)return;

        AppDataModel dataModel = app.getSubsetByRowIndexs(dataIndexs);
         int rowcount = dataModel.getRowCount();
         int colcount = dataModel.getColumnCount();

            DendroMatrix matrix= new DendroMatrix(600,60);

            matrix.setRowColumn(rowcount,colcount);
            AgglomerativeClusteringpub clusterWorker=new AgglomerativeClusteringpub();
            clusterWorker.setData(dataModel);
            AppDataModel normaldata = Normalizer.normalize((DefaultAppDataModel) dataModel);
            clusterWorker.clustering(normaldata);
             clusterWorker.getLeafs();

             Color[][] colors = VitUtils.generateDDcolors(normaldata, 5);
             BCluster rnode=clusterWorker.getRoot() ;
             java.util.List<DfLCluster> leafs= clusterWorker.getLeafs();
            java.util.List clusters=clusterWorker.getClusters();   // 
            int nbCluster=clusterWorker.getNbCluster();
            int nbLeafCluster=clusterWorker.getNbLCluster();// .getNbLeafCluster();
            double maxsim=clusterWorker.getMaxSimilarity()[1];
            double minsim=clusterWorker.getMinSimilarity();
             matrix.setInfo(rnode,leafs,clusters,nbCluster,nbLeafCluster,minsim,maxsim,clusterWorker.getLeafIds());
             matrix.setColors(colors);
            JScrollPane sp=new JScrollPane(matrix);
            JFrame fm=new JFrame();
            // JSwingUtils.showDialog(this,sp,"Matrix",null);
             JFrame mf = new JFrame();
           Container container = mf.getRootPane().getContentPane();
           container.add( sp);

           mf.setSize(800, 600);
           mf.setVisible(true);
           mf.show();


    }
    private void selBtnActionPerformed(java.awt.event.ActionEvent evt) {
       this.fireSelection();
    }

    private void combBtnActionPerformed(java.awt.event.ActionEvent evt) {
        combineSelection();
    }

    // Variables declaration - do not modify
    private javax.swing.JPanel MainPane;
    private javax.swing.JButton addBtn;
    private javax.swing.JButton clsBtn;
    private javax.swing.JButton combBtn;
    private javax.swing.JTextArea descArea;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JScrollPane jScrollPane3;
    private javax.swing.JTable jTable1;
    private javax.swing.JTextArea jTextArea1;
    private javax.swing.JSplitPane mainSplit;
    private javax.swing.JButton rmvBtn;
    private javax.swing.JButton selBtn;
    private javax.swing.JToolBar toolBar;
    private javax.swing.JButton updtBtn;




    

}

